const toolControllers = {};

const toolModels = require("../models/toolModels");
/**
 * 获取数据表
 */
toolControllers.getTable = async function (req, res) {
  let data = req.query;
  let list = [];
  try {
    list = await toolModels.getTable(data);
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
  try {
    let total = await toolModels.getTableTotal(data);
    res.send({
      code: 200,
      data: {
        list,
        total,
      },
      msg: "success",
    });
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
};

/**
 * 获取数据（修改）
 */
toolControllers.getTableInfo = async function (req, res) {
  let data = req.query;
  let table = {};
  try {
    table = await toolModels.getTableInfo(data.id);
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
  try {
    fields = await toolModels.getFieldsInfo(data.id);
    table.tableFileds = fields;
    res.send({
      code: 200,
      data: table,
      msg: "success",
    });
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
};

/**
 * 生成数据表
 */
toolControllers.buildTable = async function (req, res) {
  let data = req.body;
  // 存储表
  let table = null;
  try {
    table = await toolModels.addTable(data);
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
  // 存储字段
  try {
    await toolModels.addFields(data.tableFileds, table.id);
    res.send({
      code: 200,
      data: null,
      msg: "保存成功",
    });
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
    return;
  }
};

/**
 * 删除数据表
 */
toolControllers.deleteTables = async function (req, res) {
  let data = req.body;
  try {
    await await toolModels.deleteTables(data.ids);
    res.send({
      code: 200,
      data: null,
      msg: "删除成功",
    });
  } catch (error) {
    console.log(error.sqlMessage);
    res.send({
      code: 500,
      data: null,
      msg: error.sqlMessage,
    });
  }
};

module.exports = toolControllers;
